package com.haofengsoft.scce.common.security;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2014/10/15.
 */
public class EncryptUtil {
    private static final String HMAC_SHA1 = "HmacSHA1";
//    private static final String APP_SECRET = "123456";

    /**
     * 生成签名数据
     *
     * @param data 待加密的数据
     * @throws java.security.InvalidKeyException
     * @throws java.security.NoSuchAlgorithmException
     */
    public static String getSignature(String data) {
        try {
            //动态获取
            String APP_SECRET = "123456";
//            String APP_SECRET = PreferenceUtil.getString(Constant.USER_ACCESS_TOKEN_KEY);
//            if (null == APP_SECRET) {
//                APP_SECRET = "123456";
//            }
            String app_secret = APP_SECRET;
            byte[] key = app_secret.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1);
            Mac mac = Mac.getInstance(HMAC_SHA1);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte raw : rawHmac) {
                sb.append(byteToHexString(raw));
            }
            return sb.toString();

        } catch (Exception ex) {
            return data;
        }
    }

    private static String byteToHexString(byte ib) {
        char[] Digit = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
        };
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0f];
        ob[1] = Digit[ib & 0X0F];
        String s = new String(ob);
        return s;
    }
}
